package com.superman.serviceImpl;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import com.superman.dao.ProductDao;
import com.superman.domain.Product;
import com.superman.utils.JDBCUtils;


public class ProductDaoImpl implements ProductDao {
	private QueryRunner qr = new QueryRunner();
	private QueryRunner run = new QueryRunner(JDBCUtils.getDataSource());
	@Override
	public void release(Connection conn, String cid) {
		String sql = "update product set cid=null where cid=?";
		try {
			qr.update(conn, sql,cid);
		} catch (SQLException e) {
			e.printStackTrace();
			throw new RuntimeException("解除外键约束失败");
		}
	}
	@Override
	public int count() {
		String sql = "select count(*) from product";
		try {
			return run.query(sql, new ScalarHandler<Long>()).intValue();
		} catch (SQLException e) {
			e.printStackTrace();
			throw new RuntimeException("查询总计录数失败");
		}
		
	}
	@Override
	public List<Product> page(int startIndex, int size) {
		String sql = "select * from product limit ?,?";
		try {
			return run.query(sql, new BeanListHandler<Product>(Product.class), startIndex,size);
			
		} catch (SQLException e) {
			e.printStackTrace();
			throw new RuntimeException("分页查询商品失败");
		}
		
	}
	@Override
	public List<Product> findAllProduct() {
		String sql = "select * from product ";
		try {
			return run.query(sql, new BeanListHandler<Product>(Product.class));
		} catch (SQLException e) {
			e.printStackTrace();
			throw new RuntimeException("查询所有商品失败");
		}
	}
	@Override
	public Product update(String pid) {
		String sql = "select * from product where pid=?";
		try {
			return run.query(sql, new BeanHandler<Product>(Product.class), pid);
		} catch (SQLException e) {
			e.printStackTrace();
			throw new RuntimeException("编辑商品信息失败");
		}
	}
	@Override
	public void updateProduct(Product p) {
		String sql = "update product set pname = ?,market_price = ?,shop_price = ?,is_hot = ?,pdesc = ?,pflag = ?,cid = ? where pid = ?"
				;
		
		try {
			run.update(sql, p.getPname(),p.getMarket_price(),p.getShop_price(),p.getIs_hot(),p.getPdesc(),p.getPflag(),p.getCid(),p.getPid());
		} catch (SQLException e) {
			e.printStackTrace();
			throw new RuntimeException("修改商品信息失败");
		}
	}
	@Override
	public void deleteProduct(String pid) {
		String sql = "delete from product where pid=?";
		try {
			run.update(sql, pid);
		} catch (SQLException e) {
			e.printStackTrace();
			throw new RuntimeException("删除商品信息异常");
		}
	}
	
	

}
